import React, { useState, useEffect, useMemo } from 'react';
import { loc, obj_str, no_del, BtTxt, PanelFind, filter_row, useCmd, useHigh, Btn, GridTable } from 'sui';
import { load_auth } from './cmd';
import { DlgVal } from './ctl';
import { useAccess } from 'cache';

const UserView = () => {
    const [open_val, openVal] = useState(false);
    const [auth, setAuth] = useState();
    const [high] = useHigh(140, 100);
    const umd = useCmd("user/list", ["admin"]);
    const [no_acc] = useAccess();

    useEffect(() => {
        load_auth(setAuth);
    }, []);

    const getRow = useMemo(() => {
        const lst = ["sn", "name", "auth"];
        return filter_row(umd.value, lst, umd.filter);
    }, [umd.value, umd.filter]);

    const hDel = (val) => {
        if (no_del()) {
            return;
        }

        umd.update("user/rm", {"k": obj_str(val, "sn")});
    };

    const act = {
        "add": v => umd.update("user/add", {"v": v}),
        "edit": v => umd.update("user/md", {"v": v, "sn": obj_str(v, "sn")}),
    };

    const pact = {
        "add": v => openVal(true),
        "edit": v => openVal(true),
    };

    const col = [
        {name: loc("l_193"), key: 'index', width: 70, frozen: true},
        {name: loc("l_238"), key: 'e_opt', width: 128, frozen: true, formatter: (props) => {
            const d = props.row;
            return (
                <div className="inline-flex">
                    <BtTxt hcmd={() => umd.pact(pact, d, "edit")} disabled={no_acc("kd")}>{loc("l_235")}</BtTxt>
                    <BtTxt hcmd={() => hDel(d)} disabled={no_acc("kd")}>{loc("l_237")}</BtTxt>
                </div>
            );
        }},
        {name: `${loc("l_257")} SN`, key: 'sn', width: 200},
        {name: loc("l_318"), key: 'name', width: 200},
        {name: loc("l_258"), key: 'auth', width: 500, formatter: (props) => {
            const d = props.row;
            const t = obj_str(d, "auth");

            if (auth) {
                const f = auth.find(d => d.sn === t);
                if (f) {
                    return `${f.sn} ( ${f.name} )`;
                }
            }

            return t;
        }},
    ];

    const Right = () => <Btn hcmd={() => umd.pact(pact, null, "add")} className="ml-3" disabled={no_acc("kd")}>{loc("l_239")}</Btn>;

    return (
        <div className="flex flex-col">
            <PanelFind left={loc("l_260")} right={<Right/>}/>
            <GridTable high={high} col={col} row={getRow}/>
            <DlgVal open={open_val} hcmd={v => umd.act(act, v)} setOpen={openVal} data={umd.cur} main={umd.value} auth={auth}/>
        </div>
    );
};

export {UserView};
